package org.example.Server.service.notice;

import lombok.extern.slf4j.Slf4j;
import org.example.Server.mapper.notice.NoticeMapper;
import org.example.Server.model.notice.NoticeDTO;
import org.example.Server.model.notice.NoticeVO;
import org.example.Server.utils.ResultAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.example.Server.utils.ExceptionEnum.SQL_ERROR;

@Slf4j
@Service
public class NoticeService {
    @Autowired
    NoticeMapper noticeMapper;

    @Transactional
    public ResultAPI addnotice(NoticeDTO noticeDTO) {
        //添加notice
        boolean flag = noticeMapper.addNotice(noticeDTO);
        //如果有分班添加分班
        boolean flag2 = true;
        if (noticeDTO.getDivision_ids() != null && noticeDTO.getDivision_ids().size() != 0)
            flag2 = noticeMapper.addNoticeDivision(noticeDTO);
        if (flag && flag2) {
            return ResultAPI.success();
        }
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    public ResultAPI getNoticeList(Integer semesterId) {
        List<NoticeVO> noticeList = noticeMapper.getNoticeListAll(semesterId);
        return ResultAPI.success(noticeList);
    }

    @Transactional
    public ResultAPI updateNotice(NoticeDTO noticeDTO) {
        //更新通知内容以及标题
        boolean flag = noticeMapper.updateNotice(noticeDTO);
        boolean flag2 = true;
        //检查是否已分班
        boolean isDivide;
        isDivide = noticeMapper.isNoticeDivide(noticeDTO);
        //要分班
        if (noticeDTO.getDivision_ids() != null && noticeDTO.getDivision_ids().size() != 0) {
            //已分班
            if (isDivide) {
                noticeMapper.deleteNoticeDivision(noticeDTO);
            }
            flag2 = noticeMapper.addNoticeDivision(noticeDTO);
        }
        //不分班，统一
        else {
            //已分班
            if (isDivide) {
                noticeMapper.deleteNoticeDivision(noticeDTO);
            }
        }
        if (flag && flag2) {
            return ResultAPI.success();
        } else
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    public ResultAPI deleteNotice(Integer noticeId) {
        boolean flag = noticeMapper.deleteNotice(noticeId);
        if (flag) {
            return ResultAPI.success();
        }
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }
}
